/*
 * Created on 19-sep-2004
 *
 */
package gurulab.merlin.server.demo;

import gurulab.merlin.core.CantHandException;
import gurulab.merlin.core.envelope.AbstractEnvelopeProcessor;
import gurulab.merlin.core.envelope.Envelope;
import gurulab.merlin.core.envelope.EnvelopeHandler;
import gurulab.merlin.server.EPContainer;

/**
 * @author cobach
 *
 */
public class HelloWorldEP extends AbstractEnvelopeProcessor{
    Thread thread;
    Helloer helloer;
    
    public HelloWorldEP(EPContainer container) {
		super(container);
	}
    
    public void start(){
        System.out.println("Starting HelloWorldEP");
        if(thread==null){
            System.out.println("Instantiating HelloWorldEPs Helloer Thread");
            thread=new Thread(new Helloer(getEnvelopeHandler()));
        }
        System.out.println("Starting HelloWorldEPs Helloer Thread");
        thread.start();
    }
    
    public void stop(){
    	//implementar...
        //thread.stop();
    }

    /* (non-Javadoc)
     * @see gurulab.merlin.core.AbstractEnvelopeProcessor#handEnvelope(gurulab.merlin.core.Envelope)
     */
    public Object handEnvelope(Envelope envelope) throws CantHandException {
        System.out.println("Recib el mensaje:"+envelope.toString());
        return null;
    }

    /* (sin Javadoc)
     * @see gurulab.merlin.core.EnvelopeHandler#retrieveEnvelope(java.lang.Object)
     */
    public void retrieveEnvelope(Object EnvelopeReference) throws CantHandException {
        // TODO Apndice de mtodo generado automticamente
        
    }

    /* (sin Javadoc)
     * @see gurulab.merlin.core.EnvelopeHandler#commitHandEnvelope(java.lang.Object)
     */
    public void commitHandEnvelope(Object EnvelopeReference) throws CantHandException {
        // TODO Apndice de mtodo generado automticamente
        
    }
    
    public boolean estaOcupado() {
    	// TODO Auto-generated method stub
    	return false;
    }
}

class Helloer implements Runnable{
    EnvelopeHandler handler;
    long counter=0;
    String txt;
    
    Helloer(EnvelopeHandler h){
        handler=h;
    }
    
     public void run(){
        while(true){
            try{
                txt="Contenido #"+(counter++);
                handler.handEnvelope(new Envelope(txt,new SimpleAddress("adentro"),new SimpleAddress("afuera")));
                System.out.println("Mensaje enviado: "+txt);

                Thread.sleep(5000);
            }
            catch(Exception e){
                System.err.println("Problema enviando mensaje ("+txt+"): "+e);
            }
            
        }
    }     
}
